package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    /**
     * 通过环信id查询用户信息
     * @param huanxinId
     * @return
     */
    public UserInfoVo findUserByHuanxinUser(String huanxinId) {
        //1. 通过环信id查询用户
        User user = userApi.findByHuanxinUser(huanxinId);
        //2. 查询用户详情
        UserInfo userInfo = userInfoApi.findUserInfo(user.getId());
        //3. 转成vo
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setAge(userInfo.getAge().toString());
        return vo;
    }

    /**
     * 联系人添加
     * @return
     */
    public void addContacts(Long friendId) {
        User friendUser = userApi.findById(friendId);

        String friendHuanXinId = friendUser.getHxUser();//环信用户id
        String loginHuanXinId = UserHolder.getUser().getHxUser();//当前登录用户环信id
        log.debug("***********loginHuanXinId**{}*********friendHuanXinId**{}************",loginHuanXinId,friendHuanXinId);
        //1.调用环信云添加好友关系
        Boolean isAdd = huanXinTemplate.addContact(friendHuanXinId, loginHuanXinId);
        if(!isAdd){
            //throw new TanHuaException(ErrorResult.error());
            log.debug("********************添加好友失败了或好友关系已经存在了********************");
        }
        //2.调用服务添加双向好友关系（添加两条记录到friend表中）
        log.debug("***********friendId**{}*********getUserId**{}************",friendId,UserHolder.getUserId());
        friendApi.add(friendId,UserHolder.getUserId());
        log.debug("********************添加好友成功了*********");
    }

    /**
     *   联系人列表分页列表
     */
    public PageResult<ContactVo> findPageFriend(Long page, Long pagesize, String keyword) {
        //1根据当前登录用户id分页查询好友列表数据
        PageResult<Friend> friendPageResult = friendApi.findPageFriend(page,pagesize,UserHolder.getUserId());
        if(friendPageResult == null || CollectionUtils.isEmpty(friendPageResult.getItems())){
            return null;
        }
        //2获取所有好友ids
        List<Friend> friendList = friendPageResult.getItems();
        List<Long> friendIds = friendList.stream().map(Friend::getFriendId).collect(Collectors.toList());
        //3根据所有好友dis查询tb_userInfo 并进行keyword条件过滤（用户昵称 模糊搜索）

        UserInfo userInfoCondition  = new UserInfo();
        userInfoCondition.setNickname(keyword);//昵称
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByCondition(friendIds, userInfoCondition);
        //4基于tb_userInfo构造ContactVo
        List<ContactVo> contactVoList = new ArrayList<>();
        for (Friend friend : friendList) {
            UserInfo userInfo = userInfoMap.get(friend.getFriendId());
            if(userInfo != null) {
                contactVoList.add(ContactVo.init(userInfo));
            }
        }
        return new PageResult<>(page, pagesize, friendPageResult.getCounts(), contactVoList);
    }
}